package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gulimall.member.ao.SociUser;
import com.atguigu.gulimall.member.exception.PhoneExist;
import com.atguigu.gulimall.member.exception.UserNameExist;
import com.atguigu.gulimall.member.vo.AuthGiteeUserVo;
import com.atguigu.gulimall.member.vo.MemberRegisterVo;
import com.atguigu.gulimall.member.vo.UserLoginVo;
import lombok.extern.log4j.Log4j2;
import okhttp3.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;

@Log4j2
@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registerMember(MemberRegisterVo vo) {
        MemberEntity defaultLevel = baseMapper.getDefaultLevel();
        checkUserNameUnique(vo.getUsername());
        checkPhoneUnique(vo.getPhone());


        MemberEntity insertEntity=new MemberEntity();
        insertEntity.setLevelId(defaultLevel.getId());
        insertEntity.setUsername(vo.getUsername());
        insertEntity.setNickname(vo.getUsername());

        //密码加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        insertEntity.setPassword(encode);
        insertEntity.setMobile(vo.getPhone());
        baseMapper.insert(insertEntity);
    }

    @Override
    public MemberEntity login(UserLoginVo vo) {
        String name= vo.getLoginAcc();
        String  pass= vo.getPassword();

        MemberEntity member = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", name)
                .or().eq("mobile", name));
        if (member==null){
            return null;
        }else {
            BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
            boolean b = passwordEncoder.matches(pass, member.getPassword());
            if (b){
                return member;
            }else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity AuthLogin(SociUser sociUser) {
        sociUser.setCreated_at(1715502769);
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("soci_user", sociUser.getCreated_at()));
        if (memberEntity!=null){
            log.info("MemberServiceImpl。AuthLogin 用户信息存在");
         /*   MemberEntity updateMember=new MemberEntity();
            updateMember.setId(memberEntity.getId());
            updateMember.setAccessToken(sociUser.getAccessToken());
            updateMember.setExpiresIn(sociUser.getExpiresIn().longValue());
            baseMapper.updateById(updateMember);

            memberEntity.setExpiresIn(sociUser.getExpiresIn().longValue());
            memberEntity.setAccessToken(sociUser.getAccessToken());*/
        }else {
            MemberEntity insertMember=new MemberEntity();
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://gitee.com/api/v5/user?access_token=" + sociUser.getAccessToken()).build();
                Response response = client.newCall(request).execute();
                String giteeUserStr = Objects.requireNonNull(response.body()).string();
                AuthGiteeUserVo userInfo = JSON.parseObject(giteeUserStr, AuthGiteeUserVo.class);
                log.info("gitee查询用户信息成功 user={}",JSON.toJSONString(userInfo));
                insertMember.setNickname(userInfo.getName());
            } catch (Exception e) {
            log.info("gitee查询用户信息失败");
            }
            insertMember.setSociUser(sociUser.getCreated_at().toString());
            insertMember.setExpiresIn(sociUser.getExpiresIn().longValue());
            insertMember.setAccessToken(sociUser.getAccessToken());

            baseMapper.insert(insertMember);
            return insertMember;
        }

        return memberEntity;
    }

    private void checkUserNameUnique(String username) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new UserNameExist();
        }
    }

    private void checkPhoneUnique(String phone) {
        Integer count = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new PhoneExist();
        }
    }

}